package cn.com.xy.sms.sdk.util;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import cn.com.xy.sms.sdk.log.LogManager;

public class XyJSONObject extends JSONObject {
    private static final String TAG = "XyJSONObject";

    public static XyJSONObject getFromMap(Map<String, ?> copyFrom) {
        if (copyFrom == null || copyFrom.isEmpty()) {
            return null;
        }

        return new XyJSONObject(copyFrom);
    }

    private XyJSONObject(Map<String, ?> copyFrom) {
        super(copyFrom);
    }

    public XyJSONObject(JSONObject json) throws JSONException {
        this(json.toString());
    }

    public XyJSONObject(String json) throws JSONException {
        super(json);
    }

    public Map<String, String> getMapString() {
        Map<String, String> valueMap = new LinkedHashMap<String, String>();
        Iterator<String> keyIter = keys();
        String key;
        String value;
        while (keyIter.hasNext()) {
            key = keyIter.next();
            value = optString(key);
            valueMap.put(key, value);
        }

        return valueMap;
    }

    public Map<String, Object> getMap() {
        Map<String, Object> valueMap = new LinkedHashMap<String, Object>();
        Iterator<String> keyIter = keys();
        String key;
        Object value;
        while (keyIter.hasNext()) {
            key = keyIter.next();
            value = opt(key);
            valueMap.put(key, unwrap(value));
        }

        return valueMap;
    }

    public static Object unwrap(Object o) {
        if (o == null) {
            return NULL;
        }

        if (o instanceof String || o instanceof Integer || o instanceof Long || o instanceof Boolean
                || o instanceof Byte || o instanceof Character || o instanceof Double || o instanceof Float) {
            return o;
        }

        try {
            if (o instanceof JSONObject) {
                return new XyJSONObject((JSONObject) o).getMap();
            } else if (o instanceof JSONArray) {
                return new XyJSONArray((JSONArray) o).getList();
            } else if (o.equals(NULL)) {
                return null;
            } else {
                LogManager.w(TAG, "unwrap unknown:" + o);
            }
        } catch (Throwable t) {
            LogManager.e(TAG, "unwrap:", t);
        }

        return o;
    }
}
